(ns qwiz.views.game
  (:require [noir.response :as resp]
    [noir.session :as session]
    [qwiz.models.model :as mod]
    [qwiz.gamecore.chat :as chat]
    )
  (:use [noir.core]
    [hiccup.page-helpers]
    [hiccup.form-helpers]
    [hiccup.core]
    [qwiz.gamecore.core]
    ))


(defpartial layout [& content]
  (html5
    [:head
     [:title (concat "Qwiz, hello: " ((mod/me) :username))]
     (include-css "/css/reset.css")
     (include-js "http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dojo/dojo.js")
     (include-js "http://documentcloud.github.com/underscore/underscore.js")
     (include-js "/js/core.js")]
    [:body
     [:div#wrapper
      content]]))


(defpage "/game" []
  (if (not (mod/is-user?))
    (resp/redirect "/login")
    (layout [:div (link-to "/logout" "Logout")])))

(defn do-error [message])

(defpage [:post "/get-user-game"] {:as params}
  (if (mod/is-user?)
    (let [me (mod/me)]
      (resp/json
        (prepare-game-for-ui (get-user-game me))))
    (resp/json {:error "Do not login"})))


(defpage [:post "/get-chat"] {:as params}
  (if (mod/is-user?)
    (let [me (mod/me) res  (chat/get-messages @(me :last-chat-update))]
      (dosync  (alter (mod/meref) assoc :last-chat-update (ref (now))))
      (println res)
      (resp/json res))
    (resp/json {:error "Do not login"})))



(defpage [:post "/put-chat"] {:as message}
  (if (mod/is-user?)
    (let [me (mod/me)]
      (println message)
      (chat/put-message me (message :message))
      (resp/json {:result "OK"}))
    (resp/json {:error "Do not login"})))



(defpage [:post "/register-in-game"] {:as params}
  (if (mod/is-user?)
    (let [me (mod/me)]
      (if (user-not-in-game? me) (push-user-to-queue me))
      (resp/json
        (prepare-game-for-ui (get-user-game me))))
    (resp/json {:error "Do not login"})))

(defpage [:post "/unregistered-from-game"] {:as params}
  (if (mod/is-user?)
    (let [me (mod/me)]
      (unregistered-from-game me)
      (resp/json
        (prepare-game-for-ui (get-user-game me))))
    (resp/json {:error "Do not login"})))

;{:users @(g :users) :question @(g :q)}

